package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.UserSearchHistoryService;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserSearchHistoryServiceImpl implements UserSearchHistoryService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult del(HistorySearchDto dto) {
        //1.校验
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(StringUtils.isBlank(dto.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.删除  按id删除  只能删除当前登陆人的  搜索历史
        Query query = Query.query(Criteria.where("id").is(dto.getId()).and("userId").is(user.getId()));
        DeleteResult result = mongoTemplate.remove(query, ApUserSearch.class);
        log.info("删除搜索历史  {}", result.getDeletedCount());

        //3.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult load() {
        //1.校验  必须得登陆
        WmUser user = WmThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.查询mongo 获取该用户下的搜索历史
        Query query = Query.query(Criteria.where("userId").is(user.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);


        //3.返回
        return ResponseResult.okResult(list);
    }

    @Override
    @Async//异步保存搜索记录
    public void insert(UserSearchDto dto, Integer userId) {
        log.info("线程名 {}   保存搜索记录   id：{}", Thread.currentThread().getName(), userId);//task-1

        //1.校验
        if(dto==null){
            log.error("非法参数");
            return;
        }

        //2.查询搜索记录
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(dto.getSearchWords()));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //3.如果该用户  存在该关键字 搜索记录 则更新时间
        if(userSearch!=null){
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);//如果id存在则修改  不存在则新增
            return;
        }

        //4.查询该用户下 搜索记录是否超过10条  超过则替换最后一条，不超过则新增
        Query query1 = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query1, ApUserSearch.class);
        if(list==null || list.size()<10){//说明该用户搜索记录不超过10  新增
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setUserId(userId);
            apUserSearch.setKeyword(dto.getSearchWords());
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);//新增
        }else{
            ApUserSearch apUserSearch = list.get(list.size() - 1);//下标是从0开始
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setKeyword(dto.getSearchWords());
            mongoTemplate.save(apUserSearch);//修改
        }

    }
}
